package cn.it58.gooditname.services

import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.extensions.PluginId

/**
 * 版本管理服务
 */
object VersionService {
    
    private const val PLUGIN_ID = "cn.it58.goodname"
    
    /**
     * 获取当前插件版本
     */
    fun getCurrentVersion(): String {
        return try {
            val pluginId = PluginId.getId(PLUGIN_ID)
            val plugin = PluginManagerCore.getPlugin(pluginId)
            plugin?.version ?: "1.0.0"
        } catch (e: Exception) {
            // 如果无法获取版本，返回默认版本
            "1.0.0"
        }
    }
    
    /**
     * 比较版本号
     * @param version1 版本1
     * @param version2 版本2
     * @return 如果version1 < version2返回负数，相等返回0，大于返回正数
     */
    fun compareVersions(version1: String, version2: String): Int {
        return try {
            val v1Parts = version1.split(".").map { it.toIntOrNull() ?: 0 }
            val v2Parts = version2.split(".").map { it.toIntOrNull() ?: 0 }
            
            val maxLength = maxOf(v1Parts.size, v2Parts.size)
            
            for (i in 0 until maxLength) {
                val v1Part = v1Parts.getOrElse(i) { 0 }
                val v2Part = v2Parts.getOrElse(i) { 0 }
                
                when {
                    v1Part < v2Part -> return -1
                    v1Part > v2Part -> return 1
                }
            }
            0
        } catch (e: Exception) {
            0
        }
    }
    
    /**
     * 检查是否有新版本
     */
    fun hasNewVersion(latestVersion: String): Boolean {
        val currentVersion = getCurrentVersion()
        return compareVersions(currentVersion, latestVersion) < 0
    }
} 